<?php

namespace App\Admin\Controllers\Ty;

use App\Admin\Actions\Grid\Row\SwtTyGood\AddToGoods;
use App\Admin\Actions\Grid\Row\SwtTyGood\RefreshStatus;
use App\Admin\Actions\Grid\Tools\SwtTyGood\GetGoodsInSide;
use App\Models\SwtTyGood;
use App\Models\SwtTyGoodsImage;
use App\Services\TuoYuanService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
class SwtTyGoodController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(SwtTyGood::with(['tyGoodsImage','goods']), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->column('bar_code') -> display(function ($bar_code) {
                return $bar_code ? : '非标';
            });
            $grid->column('goods_name');
            $grid->column('weight');
            $grid->column('is_standard')->using(['非标','标品'])->label(['danger', 'success']);
            $grid->column('is_register')->using(['待审核','审核中','已通过','未通过'])->label(['info', 'warning','success','danger']);

            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('bar_code');
                $filter->like('acceptance_id');
            });

            $grid->quickSearch('goods_name');

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->selectOne('is_register', '状态', [
                    0 => '待审核',
                    1 => '审核中',
                    2 => '已通过',
                    3 => '未通过',
                ]);

                $selector->selectOne('is_standard', '标品', [
                    0 => '非标',
                    1 => '标品'
                ]);
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if($actions->row->is_register < 2) {
                    $actions->append(new RefreshStatus());
                }

                if($actions->row->is_register == 2 && empty($actions->row->goods->toArray())) {
                    $actions->append(new AddToGoods());
                }

                if($actions->row->is_register == 3) {
                    $actions -> disableDelete(false);
                }
            });

            $grid->tools(function (Grid\Tools $tools) {
                $tools->append(new GetGoodsInSide());
            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new SwtTyGood(), function (Show $show) {
            $show->field('id');
            $show->field('acceptance_id');
            $show->field('sku_id');
            $show->field('bar_code');
            $show->field('goods_name');
            $show->field('weight');
            $show->field('is_standard');
            $show->field('is_register');
            $show->field('desc');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(SwtTyGood::with(['tyGoodsImage']), function (Form $form) {
            $form->disableResetButton();

            $form->row(function (Form\Row $form) {
                $form->width(6)
                    ->text('bar_code')
                    ->required()
                    ->rules([
                        'required',
                        'max:32',
                        Rule::unique('swt_ty_goods','bar_code'),
                        Rule::unique('swt_goods','bar_code')
                    ])
                    ->help('标品必填');

                $form->width(6)
                    ->text('goods_name')
                    ->required()
                    ->rules([
                        'max:20',
                        Rule::unique('swt_ty_goods','goods_name')
                    ])
                    ->help('不得超过20字');

            });

            $form->row(function (Form\Row $form) {
                $form->width(6)
                    ->text('weight')
                    ->required();
                $form->width(6)
                    ->switch('is_standard')
                    ->default(1);
            });

            $form->row(function (Form\Row $form) {
                $form
                    ->width()
                    ->multipleImage('images','建模图片')
                    ->limit(9)
                    ->maxSize(1024 * 2)
                    ->move('upload/ty_goods/'.date('Ymd'))
                    ->uniqueName()
                    ->autoUpload()
                    ->required();
            });

            $form->saving(function (Form $form) {
                if ($form->isCreating()) {
                    $images = $form->input('images');

                    $img_urls = explode(',', $images);

                    $file_path = [];

                    foreach($img_urls as $img) {
                        $file_path[] = Storage::disk('oss')->url($img);
                    }

                    $acceptanceId = TuoYuanService::applyGoods($form -> goods_name, $file_path, $form ->weight, $form -> bar_code ?? '', $form -> is_standard);

                    $goods_data = [
                        "acceptance_id" => $acceptanceId,
                        "bar_code"      => $form->input('bar_code'),
                        "goods_name"    => $form->input('goods_name'),
                        "weight"        => $form->input('weight'),
                        "is_standard"   => $form->input('is_standard')
                    ];

                    $res = SwtTyGood::create($goods_data);

                    if(!$res) {
                        return $form->response()->error("数据新增失败");
                    }

                    $goods_id = $res->id;

                    $image_data = [];

                    foreach($img_urls as $img) {
                        $image_data[] = [
                            'ty_goods_id' => $goods_id,
                            'url'         => $img,
                            'created_at'  => date('Y-m-d H:i:s', time()),
                            'updated_at'  => date('Y-m-d H:i:s', time())
                        ];
                    }
                    SwtTyGoodsImage::insert($image_data);
                }
                return $form->response()->success('操作成功')->redirect('ty/swt_ty_good');
            });

            $form -> deleted(function (Form $form, $result) {
                $data = $form->model()->toArray();
                foreach($data as $v) {
                    foreach($v['ty_goods_image'] as $img) {
                        Storage::disk('oss') -> delete($img['url']);
                        SwtTyGoodsImage::destroy($img['id']);
                    }
                }
                if (!$result) {
                    return $form->response()->error('数据删除失败');
                }

                return $form->response()->success('删除成功');
            });
        });
    }
}
